var Home = {
    departCode : $("#departCode").val(),
    departDesc : $("#departDesc").val()==null||$("#departDesc").val()==""?"全院":$("#departDesc").val(),
    tableIndex: $("#departCode").val()==null||$("#departCode").val()==""?"科室":"主治医师" //表格第一列描述
};
$(function () {
    //科室
    $('#depart').combobox({
        data:$.parseJSON($("#departMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
        //onSelect:ManageIndex.departChange
    });
    //院区
    $('#office').combobox({
        data:$.parseJSON($("#officeMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6,
        onSelect:Home.officeChange,
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var val = $(this).combobox("getData");
            if(val.length==2){//如果就一个院区 加上全部=2
                $(this).combobox("setValue", val[1].value);
                Home.officeChange(val[1]);
                $("#oneOffice").val("yes");
            }else{
                $(this).combobox("setValue", "");
                $("#oneOffice").val("no");
            }
        }
    });
    //病种
    $('#qcEntity').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
        //onSelect:ManageIndex.departChange
    });
    /*$('#startDate').datebox('setValue',"");
    $('#endDate').datebox('setValue',"");*/
    //年
    $('#qcYear').combobox({
        data:$.parseJSON($("#yearMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6,
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var val = $(this).combobox("getData");
            $(this).combobox("setValue", val[0].value);
        }
        //onSelect:ManageIndex.departChange
    });
    //月
    $('#qcMonth').combobox({
        data:$.parseJSON($("#monthMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
        //onSelect:ManageIndex.departChange
    });

    //Home.initTopMiddle();//加载主页顶部和中部的数据
    Home.initBottomTable();//加载主页低部表格数据
    //主页最上面文字描述
    $("#homeHtmlDesc").panel({title:Home.departDesc+"单病种质量绩效统计"});
    //表格上面文字描述
    $("#homeTableDesc").panel({title:Home.departDesc+"单病种质量绩效表格数据"});
    //绑定顶部和中部蓝色数字的点击事件
    $(".homeCaseDeatil").click(function(){
        var _this = $(this);
        var key = _this.attr("id");
        /*var desc = _this.parent().prev().html();//父级的上一个同级元素*/
        var im_content=document.getElementById(key).parentNode;;
        var descText = im_content.innerText;
        var desc = descText.split("：")[0];
        Home.homeKeyDetail(key,desc);
    });
    $(".homeCaseDeatil2").click(function(){
        var _this = $(this);
        var key = _this.attr("id");
        var desc = _this.parent().prev().html();//父级的上一个同级元素
        Home.homeKeyDetail(key,desc,2);
    });

});

/**
 * //根据父级机构 查询子机构
 */
Home.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function(data){
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}

Home.search = function(){
    Home.initBottomTable();
};


/**
 * 加载主页顶部和中部的数据
 */
/*Home.initTopMiddle = function(){
    //获取主页顶部和中部的数据
    var param = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/sdsmsta2/selectSdsUpData", function (data) {
        Home.writeTopData(data);
        Home.drawMiddleChart(data.chartDatas);
        Home.drawMiddleChart2(data.entityTypeData);
    }, function (data) {
    });
    param.depart = Home.departCode;//科室ID
    param.searchType = 1;//在院病例
    ajax.set(param);
    ajax.start();
};*/
/**
 * 加载主页底部表格数据
 */
Home.initBottomTable = function(){
    //获取主页底部表格数据
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/sdsmsta2/selectSdsUpData", function (data) {
        //$('#departmentTable').bootstrapTable("destroy");//先销毁原来的表格
        //Home.drawTable(data.tableDates);
        Home.writeTopData(data);
        Home.drawMiddleChart(data.upTopEntityData);
        Home.drawMiddleChart2(data.entityTypeData);
        Home.drawMiddleChart3(data.chartDatas);
        Home.drawMiddleChart4(data.upTimeEntityData);
        //合并单元格
        /*mergeCells(data.tableDates, "locDesc", 1, $('#departmentTable'));*/
        /*$("#departmentTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
            $(this).attr("title",$(this).text());
        });*/
    }, function (data) {
    });
    /*if ($('#startDate').datebox('getValue') != ""){
        params.startDate = $('#startDate').datebox('getValue')+" 00:00:00";//开始日期
        params.endDate = $('#endDate').datebox('getValue')+" 23:59:59";//开始日期
    } else {
        params.startDate = "";//开始日期
        params.endDate = "";//开始日期
    }*/
    params.year = $("#qcYear").combobox("getValue");//年
    params.month = $("#qcMonth").combobox("getValue");//月
    params.office = $("#office").combobox("getValue");
    params.depart = $("#depart").combobox("getValue");
    params.qcEntity = $("#qcEntity").combobox("getValue");
    ajax.set(params);
    ajax.start();
};

/**
 * 写主页顶部数据
 */
Home.writeTopData = function(data){
    $("#todayUp").html(data.todayUp);
    $("#todayUpRate").html(data.todayUpRate);
    $("#monthUp").html(data.monthUp);
    $("#monthUpRate").html(data.monthUpRate);
    $("#yearUp").html(data.yearUp);
    $("#yearUpRate").html(data.yearUpRate);
    $("#totalUp").html(data.totalUp);
    /*$("#totalUpRate").html(data.totalUpRate);*/
    $("#upLoc").html(data.upLoc);
    $("#upEntity").html(data.upEntity);
    $("#upEntityRate").html(data.upEntityRate);
    $("#upTimeRate").html(data.upTimeRate);
    $("#upEntity").html(data.upEntity);
    $("#allEntity").html(data.allEntity);
};
/**
 * 画中部图形
 */
Home.drawMiddleChart = function(data){
    var lines = [
        {desc:'上报前十病种',data:[],code:'upTopEntity'}
    ];
    var chartParams = {
        //backgroundColor : '#f2f2f2',
        isHorizontal : false,
        legendShow : false,
        showLabel : true,
        yAxisName : '例',//y轴单位
        legend:{
            show : false
        },
        isDataZoom:false,//是否显示缩放
        titleLeft:'center',//标题位置
        xAxisInterval:0,//坐标轴刻度标签的显示间隔，在类目轴中有效。默认会采用标签不重叠的策略间隔显示标签。可以设置成 0 强制显示所有标签
        rotate:50,//x轴数据偏移角度
        grid:{
            containLabel: true, //注意加上，否则axisLabel有可能显示会不全
            top:"35px",
            left:"20px",
            right:"20px",
            bottom:"5px"
        },
        label:{
            show:true,
            position:'top'
        }
    };
    barChartVte($("#upTopEntityChart"), lines, data, "上报前十病种",null,chartParams);
};

Home.drawMiddleChart2 = function(data) {
    echarts.init($("#entityTypeChart")[0]).dispose();
    var chartParams = {
        backgroundColor: '#ffffff',
        isHorizontal: false,
        radius: ['30%', '60%'],
        barColor: ['#91c7ae', '#eee'],
        legendShow: false,
        showLabel: true,
        legend: {
            show: false
        }
    };
    //风险级别 饼图
    pieCharts($("#entityTypeChart"), data, "", null, chartParams);
}
/*Home.drawMiddleChart2 = function(data){
    var value = 10;//当前进度
    var maxValue = 51;//进度条最大值
    var pipe = echarts.init(document.getElementById('entityTypeChart'));
    var option = {
        title: {
            //标题内容
            text: '',
            textStyle: {
                fontWeight: 'bold',
                fontFamily: 'Microsoft YaHei',
                fontSize: 24
            },
            //标题位置
            top: '5%',
            left: '5%'
        },
        //环形中间文字
        graphic: [
            //第一行文字
            //内容 + 位置
            {
                type: 'text',
                left: 'center',
                top: '48%',
                style: {
                    //value当前进度
                    text: '已上报' + value + '个',
                    textAlign: 'center',
                    fill: '#000',
                    fontSize: 28
                }
            },
            //第二行文字
            //内容 + 位置
            {
                type: 'text',
                left: 'center',
                top: '55%',
                style: {
                    //maxValue进度条最大值
                    text: '共' + maxValue + '个',
                    textAlign: 'center',
                    fill: '#999',
                    fontSize: 24
                }
            }
        ],
        series: [{
            type: 'pie',
            radius: ['70%', '64%'],//['外圆大小', '内圆大小']
            center: ['50%', '50%'],//圆心位置['左右'， '上下']
            hoverAnimation: false,//取消鼠标悬停动画
            animationEasing: 'cubicOut',//设置动画缓动效果
            //取消显示饼图自带数据线条
            labelLine: {
                normal: {
                    show: false
                }
            },
            //增加阴影效果
            itemStyle: {
                normal: {
                    shadowBlur: 200,
                    shadowColor: 'rgba(44, 196, 196, 0.8)'
                }
            },
            data: [
                //value当前进度 + 颜色
                {
                    value: value,
                    itemStyle: {
                        normal: {
                            color: '#73DEB3'
                        }
                    }
                },
                //(maxValue进度条最大值 - value当前进度) + 颜色
                {
                    value: maxValue - value,
                    itemStyle: {
                        normal: {
                            color: '#73A0FA'
                        }
                    }
                }
            ]
        }]
    };
    pipe.setOption(option);
}*/



Home.drawMiddleChart3 = function(data){
    var lines = [
        {desc:'上报例数',data:[],code:'upNum'}
    ];
    var chartParams = {
        backgroundColor : '#f2f2f2',//背景颜色
        isHorizontal : false,
        yAxisName : '单位:例',//y轴单位
        formatterFunc : function(params){
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0;i < params.length; i++) {
                backStr += params[i].marker+params[i].seriesName + "：" +params[i].value+ "例<br>";
            }
            return backStr;
        },
        titleShow:false,
        isDataZoom:false,//是否显示缩放
        legendShow : false,
        legendPosition : 'top',
        gridLeft:"5px",
        gridRight:"5px",
        gridTop:"15px",
        gridBottom:"10px",
        rotate:60,//x轴数据偏移角度
        showLabel : true,
        legend:{
            show : false
        }
    };
    lineChartVte($("#upNumChart2"), lines, data,null,null,chartParams);
    /*//预防措施 雷达图
    var lines = [
        {desc:'预防措施',data:[]}
    ];
    radarCharts($("#preventTypeChart"),lines,data.preventData,data.preventQuotas,"",null,chartParams);
    //疾病类型 条形图 纵向
    lines = [
        {desc:'疾病类型',data:[],code:'confrimType'}
    ];
    chartParams.grid={
        containLabel: true, //注意加上，否则axisLabel有可能显示会不全
        top:"30px",
        left:"5px",
        right:"5px",
        bottom:"5px"
    };
    chartParams.label={
        show:true,
        position:'top'
    };
    barChartVte($("#confirmTypeChart"), lines, data.confirmData, "",null,chartParams);
    //治疗措施 条形图 横向
    lines = [
        {desc:'治疗措施',data:[],code:'treatType'}
    ];
    chartParams.grid={
        containLabel: true, //注意加上，否则axisLabel有可能显示会不全
        top:"30px",
        left:"5px",
        right:"5px",
        bottom:"5px"
    };
    chartParams.isHorizontal = true;
    chartParams.label.position = 'right';
    barChartVte($("#treatTypeChart"), lines, data.treatData, "",null,chartParams);*/
};

Home.drawMiddleChart4 = function(data){
    var lines = [
        {desc:'十日病种上报及时率',data:[],code:'upTimeEntity'}
    ];
    var chartParams = {
        //backgroundColor : '#f2f2f2',
        isHorizontal : false,
        legendShow : false,
        showLabel : true,
        yAxisName : '%',//y轴单位
        legend:{
            show : false
        },
        isDataZoom:false,//是否显示缩放
        titleLeft:'center',//标题位置
        xAxisInterval:0,//坐标轴刻度标签的显示间隔，在类目轴中有效。默认会采用标签不重叠的策略间隔显示标签。可以设置成 0 强制显示所有标签
        rotate:50,//x轴数据偏移角度
        grid:{
            containLabel: true, //注意加上，否则axisLabel有可能显示会不全
            top:"35px",
            left:"20px",
            right:"20px",
            bottom:"5px"
        },
        label:{
            show:true,
            position:'top'
        }
    };
    barChartVte($("#upTimeEntityChart"), lines, data, "十日病种上报及时率",null,chartParams);
};

/**
 * 表格的表头
 */
Home.columns = [
    {title: '单病种名称', field: 'entityDesc', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return "总计";
        }
    },
    {title: '符合例数', field: 'consistentNum', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeKeyDetailTable(&apos;"+"consistentNum"+"&apos;,&apos;"+row.entityDesc+"符合例数"+"&apos;,&apos;"+row.entityId+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"consistentNum");
        }
    },
    {title: '已上报', field: 'reported', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"reported");
        }
    },
    {title: '上报率', field: 'reportedRate', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeKeyDetail(&apos;inHospitalEval&apos;,&apos;"+""+
                "入院审核&apos;,&apos;"+""+"&apos;,2)'>"+value+"&nbsp;&nbsp;("+MathMethod(row.reported,row.consistentNum)+")</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"reportedRate");
        }
    },
    {title: '次均住院日', field: 'averageHosDays', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"averageHosDays");
        }
    },
    {title: '次均住院费用', field: 'averageHosCost', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"averageHosCost");
        }
    },
    {title: '死亡例数', field: 'deathNum', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"deathNum");
        }
    },
    {title: '病死率', field: 'deathNumRate', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeKeyDetail(&apos;inHospitalEval&apos;,&apos;"+""+
                "入院审核&apos;,&apos;"+""+"&apos;,2)'>"+value+"&nbsp;&nbsp;("+MathMethod(row.deathNum,row.consistentNum)+")</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"deathNumRate");
        }
    },
    {title: '平均耗材费', field: 'averageConsumCost', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"averageConsumCost");
        }
    },
    {title: '平均药费', field: 'averageMedeCost', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            return "<a onclick='Home.homeDepartDetail(&apos;"+""+"&apos;,&apos;"+""+"&apos;)'>"+value+"</a>";
        },
        footerFormatter:function(value){
            return Home.sumFieldValue(value,"averageMedeCost");
        }
    }
];
/**
 * 科室详细信息
 */
Home.homeDepartDetail = function(departCode,departDesc){
    var href = Sys.backendPath + "/homevte?departCode="+departCode+"&departDesc="+departDesc;
    layer.open({
        type: 2,
        title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+departDesc+'详细','padding-left:10px'],
        area:["98%","98%"],
        scrollbar: false,//为了禁止父页面滚动条滚动
        skin:'classfyLBStyle layer-ext-hisui',
        content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
    });

    //Sys.addTabPage($.trim(departDesc+"详细"), href,true);
};
/**
 * 钻取主页蓝色数字详细信息
 */
Home.homeKeyDetail = function(key,desc){
    var qcYear = $("#qcYear").combobox("getValue");
    var qcMonth = $("#qcMonth").combobox("getValue");
    var office = $("#office").combobox("getValue");
    var depart = $("#depart").combobox("getValue");
    var qcEntity = $("#qcEntity").combobox("getValue");

    var href = Sys.backendPath + "/analysis/sdsmsta2/to_case?key="+key+"&searchType=1&desc="+desc +"&qcYear=" + qcYear +"&qcMonth=" + qcMonth +"&office=" + office +"&depart=" + depart +"&qcEntity=" + qcEntity;

    layer.open({
        type: 2,
        title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+desc,'padding-left:10px'],
        area:["95%","95%"],
        scrollbar: false,//为了禁止父页面滚动条滚动
        skin:'classfyLBStyle layer-ext-hisui',
        content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
    });
    //Sys.addTabPage($.trim(desc), href,true);

}

/**
 * 钻取主页蓝色数字详细信息
 */
Home.homeKeyDetailTable = function(key,desc,entityId){
    //type=1是从顶部蓝色数字传入，type=2表示从下面表格传入，如果是钻取的科室，传area参数暂时定为主治医师Id
    var startDate = "";
    var endDate = "";
    if ($('#startDate').datebox('getValue') != ""){
        startDate = $('#startDate').datebox('getValue')+" 00:00:00";//开始日期
        endDate = $('#endDate').datebox('getValue')+" 23:59:59";//开始日期
    }
    var office = $("#office").combobox("getValue");
    var depart = $("#depart").combobox("getValue");
    var qcEntity = $("#qcEntity").combobox("getValue");

    var href = Sys.backendPath + "/analysis/sdsmsta2/to_case?key="+key+"&searchType=1&desc="+desc +"&startDate=" + startDate +"&endDate=" + endDate +"&office=" + office +"&depart=" + depart +"&qcEntity=" + qcEntity+"&entityId=" + entityId;

    layer.open({
        type: 2,
        title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+desc,'padding-left:10px'],
        area:["95%","95%"],
        scrollbar: false,//为了禁止父页面滚动条滚动
        skin:'classfyLBStyle layer-ext-hisui',
        content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
    });
    //Sys.addTabPage($.trim(desc), href,true);

}


/**
 * 绘制主页的表格
 */
Home.drawTable = function(tableData){
    this.$table =
        $('#departmentTable').bootstrapTable({
            data:tableData,
            striped: false,//是否显示行间隔色
            pagination: false,//是否显示分页
            showFooter: true,
            //paginationLoop: false,
            //pageSize : 5,//用于设置每页初始显示的条数
            //pageList :[4],
            //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
            sortName: "patientNum",
            sortOrder: 'desc',// desc  asc
            maintainSelected: true,//设为true 为选中的状态
            cache: false,
            search: false, //搜索框
            columns: Home.columns,
            onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                // $(".th-inner").css("font-weight","700");//表头字体加粗
                $("#departmentTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                    $(this).attr("title",$(this).text());
                });
            }
        });
};

/**
 * 导出主页的表格数据
 */
Home.exportTable = function() {
    $("#tableDiv table").tableExport(
        {
            type : 'xlsx',
            escape : 'false'
        },Home.getSystemTime()+Home.departDesc+'VTE指标统计表'
    )
};
/**
 * 获取当天年月日
 */
Home.getSystemTime = function(){
    function p(s) {
        return s < 10 ? '0' + s: s;
    }
    var date = new Date(); // 获取中国标准时间
    var y = date.getFullYear(); // 年
    var m = date.getMonth()+1; // 月
    var d = date.getDate(); // 日
    var sysTime = y+'-'+p(m)+'-'+p(d);
    return sysTime;
};
/**
 * 计算比率
 */
function MathMethod(a,b){
    if(b==0){
        return "0%";
    }
    var num = a/b;
    num = (num.toFixed(4)) * 100;  // 输出结果为 2.45
    var numStr = num.toString()
    var index = numStr.indexOf('.');
    if(index > -1){
        numStr = numStr.substring(0, index+3);
    }
    return numStr+"%";
}

Home.sumFieldValue = function(value,field){
    var disSum = 0;
    var count = 0;
    for(var i in value){
        count += value[i][field]*1000;
        disSum += value[i]["consistentNum"]*1000;
    }
    if(count==0){//如果是0返回空
        return ""
    }
    count = count/1000;
    disSum = disSum/1000;

    if(field=="reportedRate" || field=="deathNumRate"){
        var pre = (count/disSum * 100).toFixed(2);
        return pre+"%&nbsp;&nbsp;("+count+")";
    }

    return count;
};

function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]     //fieldName的value
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    /*for(var prop in sortMap){
        console.log(prop,sortMap[prop])
    }*/
    //合并单元格
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }

}